﻿using ERPWinFormWork.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Produce
{
    public class ApiClient
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl;
        private string _token; // Token存储属性

        // 初始化，传入API基础地址
        public ApiClient(string baseUrl)
        {
            _baseUrl = baseUrl;
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(baseUrl);
            // 设置超时时间
            _httpClient.Timeout = TimeSpan.FromSeconds(30);

            // 尝试自动从TokenManager获取Token
            TrySetTokenFromManager();
        }

        // 尝试从TokenManager设置Token
        private void TrySetTokenFromManager()
        {
            if (!string.IsNullOrEmpty(TokenManager.JwtToken))
            {
                _token = TokenManager.JwtToken;
            }
        }



        // 自动从TokenManager更新Token的方法
        public void UpdateTokenFromManager()
        {
            TrySetTokenFromManager();
        }

        // GET请求（泛型方法，自动反序列化JSON）
        public async Task<T> GetAsync<T>(string endpoint, Dictionary<string, string> parameters = null)
        {
            try
            {
                var requestUrl = endpoint;
                if (parameters != null && parameters.Count > 0)
                {
                    requestUrl += "?" + string.Join("&", parameters.Select(kv => $"{kv.Key}={kv.Value}"));
                }

                // 创建请求消息
                var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                // 添加Token到请求头
                if (!string.IsNullOrEmpty(_token))
                {
                    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _token);
                }

                // 发送请求
                var response = await _httpClient.SendAsync(request);
                response.EnsureSuccessStatusCode(); // 若 API 报错（如 404），会抛出提示

                // 解析 JSON 数据
                var json = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"API 返回数据：{json}"); // 调试用，确认返回内容
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"GET请求失败：{ex.Message}");
                return default;
            }
        }

        // POST请求（发送JSON数据）
        public async Task<TResult> PostAsync<TData, TResult>(string endpoint, TData data)
        {
            try
            {
                // 使用 Newtonsoft.Json 序列化数据为JSON
                var json = JsonConvert.SerializeObject(data);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                // 创建请求消息
                var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
                request.Content = content;
                // 添加Token到请求头
                if (!string.IsNullOrEmpty(_token))
                {
                    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _token);
                }

                var response = await _httpClient.SendAsync(request);
                response.EnsureSuccessStatusCode();

                var resultJson = await response.Content.ReadAsStringAsync();
                // 使用 Newtonsoft.Json 反序列化结果
                return JsonConvert.DeserializeObject<TResult>(resultJson);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"POST请求失败：{ex.Message}");
                return default;
            }
        }

        // GetBytesAsync请求（添加Token认证）
        public async Task<byte[]> GetBytesAsync(string endpoint, Dictionary<string, string> parameters = null)
        {
            try
            {
                var requestUrl = endpoint;
                if (parameters != null && parameters.Count > 0)
                {
                    // 处理参数转义（中文、空格等）
                    requestUrl += "?" + string.Join("&",
                        parameters.Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value ?? string.Empty)}")
                    );
                }

                // 调试用：打印Excel下载请求URL
                var fullUrl = _httpClient.BaseAddress + requestUrl;
                Console.WriteLine($"Excel下载请求URL：{fullUrl}");

                // 创建GET请求消息
                var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);

                // 添加Token认证头
                if (!string.IsNullOrEmpty(_token))
                {
                    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _token);
                }

                // 发送GET请求，获取Excel流
                var response = await _httpClient.SendAsync(request);
                response.EnsureSuccessStatusCode(); // 后端返回400（无数据）、500（错误）会抛出异常

                // 读取二进制流（Excel文件的字节数组）
                byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
                Console.WriteLine($"获取到Excel字节数：{fileBytes.Length} 字节");
                return fileBytes;
            }
            catch (Exception ex)
            {
                // 捕获后端返回的错误信息（如“无导出数据”）
                string errorMsg = ex.Message;
                // 若为HttpRequestException，尝试读取后端返回的错误内容
                if (ex is HttpRequestException httpEx && httpEx.InnerException != null)
                {
                    errorMsg += $"\n后端提示：{httpEx.InnerException.Message}";
                }
                MessageBox.Show($"Excel下载请求失败：{errorMsg}");
                return null; // 失败时返回null，前端可判断
            }
        }
    }
}
